import { store } from '@/store/index';
import router from '.';
import { IsNotEmpty } from '@/utils/utils';
import { keepAliveViews } from './cache';
import { getKeepAliveViews } from './utils';

const modules = import.meta.glob('../view/**/**.vue');
interface MenuType {
    pid: number;
    type: number;
    path: any;
    code: any;
    router: any;
    name: any;
    children?: any;
}

// 是否有菜单权限
const hasPermission = (to: any) => {
    // 路由规则
    const sysRoutes = router.getRoutes();
    // 路由是否存在
    return sysRoutes.some(item => item.path === to.path || item.name === to.name);
};

// 动态路由
const addDynamicRouter = (menus: any, rootMenuId: number) => {
    if (!IsNotEmpty(menus)) return;
    menus.forEach((item: MenuType) => {
        if (rootMenuId > 0 && item.pid != 0 && item.type == 2) {
            const componentNow = modules[/* @vite-ignore */ `../view/${item.path}/index.vue`];
            router.addRoute('root', {
                name: item.code,
                path: item.router,
                component: componentNow,
                meta: {
                    title: item.name,
                    rootMenuId: rootMenuId,
                    buttonCode: item.button_list,
                    code: item.code,
                    keepAlive: keepAliveViews.some(ite => ite.cachePageCode === item.code)
                }
            });
        }
        if (rootMenuId < 0 && item.pid == 0) {
            if (IsNotEmpty(item.children)) addDynamicRouter(item.children, item.id);
        } else {
            if (IsNotEmpty(item.children)) addDynamicRouter(item.children, rootMenuId);
        }
    });
};

const getUserInfoFn = () => {
    const userMenuList = store.getters['user/getUserMenuList'];
    const accountInfo = store.getters['user/getAccountInfo'];
    if (!userMenuList.length) {
        store.dispatch('user/getUserGlobalMenuFn');
    }
    if (!accountInfo?.base_info) {
        store.dispatch('user/getAccountInfo');
    }
};

router.beforeEach(async (to: any, from: any, next: any) => {
    const keepAliveIncludes = store.getters['pageCache/keepAliveIncludes'];
    const views = getKeepAliveViews(to, from, keepAliveIncludes);
    store.dispatch('pageCache/setKeepAliveViews', views);
    const whiteListRoute = [
        '/nologin',
        '/login',
        '/agreement',
        '/register',
        '/auth/callback',
        '/forget',
        '/wx-video-shop-info' // 视频号小店信息页（去使用审核落地页）
    ]; // 路由白名单
    const token = store.getters['user/getToken'];
    const currentCorp = store.getters['user/getCurrentCorp'];
    const fromRoute = from.path.split('/');
    // 非刷新进入并且非当前子页面进入，或首页跳转进入，重置分组 ID
    if ((fromRoute[3] && fromRoute[3] != to.path.split('/')[3]) || fromRoute[1] == 'home') {
        store.dispatch('setGroupId', 0);
    }
    if (token) {
        // token 是否存在
        if (to.meta?.buttonCode && Array.isArray(to.meta.buttonCode))
            store.commit('menu/SET_BUTTON_CODE', to.meta.buttonCode);
        // 如果是登录或注册页，跳转首页
        if (['/login', '/register'].includes(to.path)) {
            next('/home');
        } else {
            // 未选企业，并且非选择企业页面，则跳转到选择企业页
            if (!currentCorp && to.path != '/selectFirm') {
                next({ path: '/selectFirm' });
            } else {
                if (!to.path.includes('selectFirm')) {
                    // 获取用户信息
                    getUserInfoFn();
                }
                const menus = store.state.menu.menus;
                if (menus?.length || to.path == '/selectFirm') {
                    addDynamicRouter(store.state.menu.menus, -1);
                    // 判断菜单权限
                    if (hasPermission(to)) {
                        // 设置默认选择菜单
                        if (!to.meta.title) {
                            next({ ...to, replace: true });
                        } else {
                            if (to.meta.rootMenuId !== store.state.currentMenuId) {
                                store.dispatch('setCurrentMenuId', to.meta.rootMenuId);
                            }
                            next();
                        }
                    } else {
                        next({ path: '/', replace: true, query: { noGoBack: true } });
                    }
                } else {
                    try {
                        // 获取用户菜单
                        const res = await store.dispatch('menu/getMenu');
                        addDynamicRouter(store.state.menu.menus, -1);
                        // 添加可访问的路由表
                        next({ ...to, replace: true });
                    } catch (error) {
                        const token = store.getters['user/getToken'];
                        // 移除 token，跳转登录页重新登录
                        token && (await store.dispatch('user/logout'));
                        store.commit('user/setUserToken', '');
                        store.commit('user/clearUser');
                        store.commit('menu/clearMenu');
                        sessionStorage.clear();
                        localStorage.clear();
                        next({ path: '/login' });
                    }
                }
            }
        }
    } else {
        // 白名单直接放行
        if (whiteListRoute.indexOf(to.path) >= 0) {
            next();
        } else {
            store.commit('user/clearUser');
            store.commit('menu/clearMenu');
            sessionStorage.clear();
            localStorage.clear();
            next(`/login`);
        }
    }
});
